﻿//check if localstorage is available and clear it
if (window.localStorage) {
    localStorage.clear();
}
var map, places, iw;
var markers = [];
var autocomplete;
var geocoder;
var searchOptions = ['venues', 'printshop', 'meal_delivery'];
var position = "";
// initialize the map and display the zipcode
function initialize() {
    initPlaceSearch();
    geocoder = new google.maps.Geocoder();
    var myLatlng = new google.maps.LatLng(37.4419, -122.1419); //33.699881, -84.456818
    var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    places = new google.maps.places.PlacesService(map);
    google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
    autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        showSelectedPlace();
    });
    //get map zip
    codeAddress();
}





function tilesLoaded() {
    google.maps.event.clearListeners(map, 'tilesloaded');
    google.maps.event.addListener(map, 'zoom_changed', search);
    google.maps.event.addListener(map, 'dragend', search);
    search();
}


function showSelectedPlace() {
    clearResults();
    clearMarkers();
    var place = autocomplete.getPlace();
    //map return values
    map.panTo(place.geometry.location);
    markers[0] = new google.maps.Marker({
        position: place.geometry.location,
        map: map
    });
    iw = new google.maps.InfoWindow({
        //create map popup
        content: getIWContent(place)
    });
    iw.open(map, markers[0]);
}
function refreshMyMap() {

    var myLatlng = new google.maps.LatLng(33.699881, -84.456818);
    var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var request = {
        location: myLatlng,
        radius: '500',
        query: 'venues'
    };
    service = new google.maps.places.PlacesService(map);
    service.textSearch(request, callback);
}

function sendUserToFormPage() {
    // sent user to confirmation page
    window.parent.changeFrameSrc('PlacesConfirmation.html');

}
function resetMyMap() {

    var myLatlng = new google.maps.LatLng(33.699881, -84.456818);
    var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    clearResults();
    clearMarkers();
    //loop over radio buttons and set them to not selected
    for (var i = 0; i < document.controls.type.length; i++) {
        document.controls.type[i].checked = false;

    }
    position = "";
    document.getElementById("sVenue").className = "wizSpanDisabled";
    document.getElementById("sPrint").className = "wizSpanDisabled";
    document.getElementById("sCater").className = "wizSpanDisabled";
    document.getElementById("Next").disabled = false;
}
function codeAddress() {

    // validate if the user came from the home page
    if (sessionStorage.zipcode) {
        document.getElementById("address").value = sessionStorage.zipcode;

    }
    //remove the stored zip
    sessionStorage.removeItem("zipcode");
    var address = document.getElementById("address").value;
    if (address == "") {
        alert("Please enter a Zip Code to get started");
        return;
    }
    hideDocElements('ca');
    //var address = document.getElementById("address").value;
    geocoder.geocode({ 'address': address },
                              function (results, status) {
                                  if (status == google.maps.GeocoderStatus.OK) {
                                      map.setCenter(results[0].geometry.location);
                                      var marker = new google.maps.Marker({
                                          map: map,
                                          position: results[0].geometry.location
                                      });
                                  } else {
                                      alert("Geocode was not successful for the following reason: " + status);
                                  }
                              }
                                )/*END geo function*/
}


function startSearch() {
    /*if position is blank this is the first step in the wizard tree*/
    if (position == "") {
        position = "venues";
        document.getElementById("sVenue").className = "wizSpan";
        document.getElementById("sPrint").className = "wizSpanDisabled";
        document.getElementById("sCater").className = "wizSpanDisabled";

        
        document.getElementById("Next").disabled = true;
    }
    else if (position == "venues") {
        position = "printshop";
        document.getElementById("sVenue").className = "wizSpanDisabled";
        document.getElementById("sPrint").className = "wizSpan";
        document.getElementById("sCater").className = "wizSpanDisabled";

        document.getElementById("Next").disabled = true;
    }
    else if (position == "printshop") {
        position = "meal_delivery";
        document.getElementById("sVenue").className = "wizSpanDisabled";
        document.getElementById("sPrint").className = "wizSpanDisabled";
        document.getElementById("sCater").className = "wizSpan";

        document.getElementById("Next").disabled = true;
    }
    else {
        position = "";
        document.getElementById("sVenue").className = "wizSpanDisabled";
        document.getElementById("sPrint").className = "wizSpanDisabled";
        document.getElementById("sCater").className = "wizSpanDisabled";

        
        document.getElementById("Next").disabled = true;

        resetMyMap();
        sendUserToFormPage();
        return;
    }

    //loop over radio buttons and set the position from wizard
    for (var i = 0; i < document.controls.type.length; i++) {
        if (document.controls.type[i].value == position) {
            document.controls.type[i].checked = true;
            break;
        }
    } //loop ends
    search();
}

//callback function from google places    
function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {

        clearResults();
        clearMarkers();
        //loop over result set
        for (var i = 0; i < results.length; i++) {
            markers[i] = new google.maps.Marker({
                position: results[i].geometry.location,
                animation: google.maps.Animation.DROP
            });

            google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
            setTimeout(dropMarker(i), i * 100);
            addResult(results[i], i);
        } //loop ends
    } //end status check



}

function search() {
    var type;

    // loop over radio buttons and select the type
    for (var i = 0; i < document.controls.type.length; i++) {
        if (document.controls.type[i].checked) {

            type = document.controls.type[i].value;
        } //end check
    } //loop end

    autocomplete.setBounds(map.getBounds());

    var search = {
        bounds: map.getBounds()
    };

    //establishment is a dummy record
    if (type != 'establishment') {
        if (type == "zipRB") {
            search.keyword = document.getElementById("address").value;
        }
        else {

            search.keyword = [type];
        }
    }
    places.search(search, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {

            clearResults();
            clearMarkers();
            //loop over results
            for (var i = 0; i < results.length; i++) {
                markers[i] = new google.maps.Marker({
                    position: results[i].geometry.location,
                    animation: google.maps.Animation.DROP
                });
                google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
                setTimeout(dropMarker(i), i * 100);
                addResult(results[i], i);
            }

        } else {
            var t = 1;
        }
    })
}

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        if (markers[i]) {
            markers[i].setMap(null);
            markers[i] == null;
        }
    }
}

function dropMarker(i) {
    return function () {
        markers[i].setMap(map);
    }
}

function addResult(result, i) {
    var results = document.getElementById("results");
    var tr = document.createElement('tr');

    tr.style.backgroundColor = (i % 2 == 0 ? '#F0F0F0' : '#FFFFFF');
    tr.onclick = function () {
        // alert("add to array here");
        google.maps.event.trigger(markers[i], 'click');
    };

    var iconTd = document.createElement('td');
    var nameTd = document.createElement('td');
    var icon = document.createElement('img');
    icon.src = result.icon;
    icon.setAttribute("class", "placeIcon");

    var name = document.createTextNode(result.name);
    iconTd.appendChild(icon);
    nameTd.appendChild(name);
    tr.appendChild(iconTd);
    tr.appendChild(nameTd);
    results.appendChild(tr);
}

function clearResults() {
    var results = document.getElementById("results");
    while (results.childNodes[0]) {
        results.removeChild(results.childNodes[0]);
    }
}

function getDetails(result, i) {
    return function () {
        places.getDetails({
            reference: result.reference
        }, showInfoWindow(i));
    }
}

function showInfoWindow(i) {
    return function (place, status) {
        if (iw) {
            iw.close();
            iw = null;
        }

        if (status == google.maps.places.PlacesServiceStatus.OK) {
            iw = new google.maps.InfoWindow({
                content: getIWContent(place)
            });
            iw.open(map, markers[i]);
        }
    }
}

var placeArray = new Array();
function getIWContent(place) {
    var content = "";
    placeArray.push(place);
    var idLen = placeArray.length - 1;

    // create popup
    content += '<table><tr><td><button type="button"  name="selMapItem" id="AddItem" onclick="addDataToLocalStorage(' + idLen + ')">Add</button></td><td>';       // content += '<img class="placeIcon" src="' + place.icon + '"/></td>';
    content += '<b>' + place.name + '</b>';
    content += '</td></tr></table>';

    return content;
}
//hide used buttons so wizard can flow 
function hideDocElements(btn) {
    var inlineNone = document.getElementById("lookupZip").style.display;
    if (inlineNone == "inline" && btn == 'ca') {
        document.getElementById("lookupZip").style.display = "none";
        document.getElementById("tblNextBtn").style.display = "inline";
    }
    else if (inlineNone == "none" && btn == 'r') {
        document.getElementById("lookupZip").style.display = "inline";
        document.getElementById("tblNextBtn").style.display = "none";
        resetMyMap();
    }


}

function addDataToLocalStorage(p) {
    // check if local storage available

    if (window.localStorage) {
        var key, value;

        // set key to position name and number       
        key = position + ':' + p;
        // create an array with the icon, url and name       
        var valueArray = [placeArray[p].icon, placeArray[p].url, placeArray[p].name];
        //separate by using the pipe
        value = valueArray.join("|");
        //set the localstorage item
        localStorage.setItem(key, value);

    }

    else {
        alert('localStorage is not supported.');
    }
    document.getElementById("Next").disabled = false;
    startSearch();
}
// button variable for listener

var btnStart;
var btnNext;
var btnReset;
var rdVenBtnSearch;
var rdPsBtnSearch;
var rdMdBtnSearch;
function initPlaceSearch() {
    btnStart = document.getElementById('getZip');
    btnStart.addEventListener('click', codeAddress, false);

    btnNext = document.getElementById('Next');
    btnNext.addEventListener('click', startSearch, false);

    btnReset = document.getElementById('Reset');
    btnReset.addEventListener('click', function () { hideDocElements('r'); }, false);

    rdVenBtnSearch = document.getElementById('venue');
    rdVenBtnSearch.addEventListener('click', search, false);

    rdPsBtnSearch = document.getElementById('printshop');
    rdPsBtnSearch.addEventListener('click', search, false);

    rdMdBtnSearch = document.getElementById('mealDelivery');
    rdMdBtnSearch.addEventListener('click', search, false);


}
window.addEventListener('load',initialize, false);